package com.unitop.partner.common.otms;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class JAXBContextFactory {
    private static JAXBContextFactory instance = new JAXBContextFactory();

    private static final Map<String, JAXBContext> INSTANCES = new ConcurrentHashMap<String, JAXBContext>();

    private JAXBContextFactory() {
    }

    /**
     * Returns an existing JAXBContext if one for the particular namespace
     * exists, else it creates an instance adds it to a internal map.
     * 
     * @param contextPath
     *            the context path
     * @throws JAXBException
     *             exception in creating context
     * @return a created JAXBContext
     */
    public static JAXBContext getJAXBContext(final Class<?> contextPath) throws JAXBException {
        JAXBContext context = INSTANCES.get(contextPath.getName());
        if (context == null) {
            context = JAXBContext.newInstance(contextPath);
            INSTANCES.put(contextPath.getName(), context);
        }
        return context;
    }

    /**
     * remove JAXBContext object
     * @param contextPath
     * @return
     */
    public static JAXBContext removeJAXBContext(final Class<?> contextPath) {
        return INSTANCES.remove(contextPath.getName());
    }

    /**
     * Get instance.
     * 
     * @return Instance of this factory
     */
    public static JAXBContextFactory getInstance() {
        return instance;
    }
}